package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
	implements ApartmentInfoService {

	// todo2 在此写Service是因为service里面才有批量添加 saveBatch的方法 在Mapper就没有这个方法
	// 公寓关系表配套实体类
	@Autowired
	private ApartmentFacilityService apartmentFacilityService;
	// 公寓标签关系表
	@Autowired
	private ApartmentLabelService apartmentLabelService;
	// 公寓杂费关系表
	@Autowired
	private ApartmentFeeValueService apartmentFeeValueService;
	// 图片表
	@Autowired
	private GraphInfoService graphInfoService;


	// 省市区名字完善 扩展
	// 在添加方法中 因为我们前端传过来的省市区只是id值 所以在数据库内是空的值，
	// 因此我们在添加的时候就需要把省市区名字一起获取到并添加到数据库内
	// mapper方法
	@Autowired
	private ProvinceInfoMapper provinceInfoMapper;
	@Autowired
	private CityInfoMapper cityInfoMapper;
	@Autowired
	private DistrictInfoMapper districtInfoMapper;


	// 下方的都是进行公寓信息回显的
	@Autowired
	private FacilityInfoMapper facilityInfoMapper;

	@Autowired
	private LabelInfoMapper labelInfoMapper;

	@Autowired
	private FeeValueMapper feeValueMapper;

	@Autowired
	private GraphInfoMapper graphInfoMapper;

	@Autowired
	private ApartmentInfoMapper apartmentInfoMapper;

	@Autowired
	private RoomInfoMapper roomInfoMapper;


	/*    既要修改
	 *   也要实现添加
	 * */
	@Override
	public void saveOrUpdateInfo(ApartmentSubmitVo apartmentSubmitVo) {
		// 先判断他是不是修改
		Long id = apartmentSubmitVo.getId();


		// 省市区扩展
		// 通过id拿到省市区记录
		// 查询公寓所属的省的信息（名字） provinceId
		ProvinceInfo provinceInfo = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId());
		apartmentSubmitVo.setProvinceName(provinceInfo.getName());
		// 查询公寓所属的城市名字
		CityInfo cityInfo = cityInfoMapper.selectById(apartmentSubmitVo.getCityId());
		apartmentSubmitVo.setCityName(cityInfo.getName());
		// 查询公寓所属的区县名字
		DistrictInfo districtInfo = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId());
		apartmentSubmitVo.setDistrictName(districtInfo.getName());


		// 添加或修改公寓的基本信息

		// todo 知识点1：
		// mybatis自动查询最新添加的id会把id赋值给被添加的对象的id属性，
		// 所以添加完以后apartmentSubmitVo里面id是有值的，等会对这个vo就可以做操作
		this.saveOrUpdate(apartmentSubmitVo);


		// id不为空 为修改 需要先把原先的外键表信息都删除掉 再去添加最新的记录
		if (id != null) {
			// 第一步：先删除跟当前公寓有关联的外键表信息
			// 再添加最新的关联信息
			// 删除公寓配套关系表信息
			apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId, id));
			// 删除公寓标签关系表信息
			apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id));
			// 删除公寓杂费关系表信息
			apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId, id));
			// 删除公寓图片关系表信息
			graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId, id).eq(GraphInfo::getItemType, ItemType.APARTMENT));
		}
		// 添加公寓配套关系表
		// 获取公寓配套列表信息 并 插入
		List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
		if (!CollectionUtils.isEmpty(facilityInfoIds)) {
			ArrayList<ApartmentFacility> apartmentFacilities = new ArrayList<>();
			for (Long facilityInfoId : facilityInfoIds) {
				// 其中使用的id不能是原先的id 要的是增加记录后回返的记录id
				ApartmentFacility apartmentFacility = ApartmentFacility.builder().apartmentId(apartmentSubmitVo.getId()).facilityId(facilityInfoId).build();
				apartmentFacilities.add(apartmentFacility);
			}
			apartmentFacilityService.saveBatch(apartmentFacilities);
		}


		// 添加公寓标签关系表
		// 获取公寓标签列表信息 并插入
		List<Long> labelIds = apartmentSubmitVo.getLabelIds();
		if (!CollectionUtils.isEmpty(labelIds)) {
			ArrayList<ApartmentLabel> apartmentLabels = new ArrayList<>();
			for (Long labelId : labelIds) {
				ApartmentLabel apartmentLabel = ApartmentLabel.builder().apartmentId(apartmentSubmitVo.getId()).labelId(labelId).build();
				apartmentLabels.add(apartmentLabel);
			}
			apartmentLabelService.saveBatch(apartmentLabels);
		}


		// 添加公寓杂费关系表
		// 获取公寓杂费列表信息 并插入
		List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
		if (!CollectionUtils.isEmpty(feeValueIds)) {
			// feeValueId的集合
			ArrayList<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>();

			for (Long feeValueId : feeValueIds) {
				ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().apartmentId(apartmentSubmitVo.getId()).feeValueId(feeValueId).build();
				apartmentFeeValues.add(apartmentFeeValue);
			}

			apartmentFeeValueService.saveBatch(apartmentFeeValues);
		}


		// 添加公寓图片表
		// 获取公寓图片列表信息 并插入
		List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
		if (!CollectionUtils.isEmpty(graphVoList)) {
			ArrayList<GraphInfo> graphInfos = new ArrayList<>();

			for (GraphVo graphVo : graphVoList) {
				GraphInfo graphInfo = new GraphInfo();

				String url = graphVo.getUrl();
				// graphInfo.setName(graphVo.getName());
				// 让name名字都不重复
				String fileName = url.substring(url.lastIndexOf("/") + 1);
				graphInfo.setName(fileName);

				graphInfo.setUrl(url);
				// 不能用之前的id 因为之前的id获取到的有可能是空的
				graphInfo.setItemId(apartmentSubmitVo.getId());
				graphInfo.setItemType(ItemType.APARTMENT);
				graphInfos.add(graphInfo);
			}

			graphInfoService.saveBatch(graphInfos);
		}

	}


	// 因为有分页插件 所以需要配置拦截器去实现
	@Override
	public IPage<ApartmentItemVo> pageItem(Page<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {
		return apartmentInfoMapper.pageItem(apartmentItemVoPage, queryVo);
	}


	// 回显方法：根据公寓的id查询公寓基本信息以及相关信息
	@Override
	public ApartmentDetailVo getDetailById(Long id) {
		ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();

		// 查询公寓的基本信息
		ApartmentInfo apartmentInfo = this.getById(id);

		// 查询公寓配套信息
		List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);
		// 查询公寓标签信息
		List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);
		// 查询公寓杂费信息
		List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);
		// 查询公寓图片信息
		// 第一个是公寓id 第二个是所属公寓还是房间类型的id
		List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndItemId(id, ItemType.APARTMENT);

		BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);

		// 设置公寓配套信息
		apartmentDetailVo.setFacilityInfoList(facilityInfoList);
		// 设置公寓标签信息
		apartmentDetailVo.setLabelInfoList(labelInfoList);
		// 设置公寓杂费信息
		apartmentDetailVo.setFeeValueVoList(feeValueVoList);
		// 设置公寓图片信息
		apartmentDetailVo.setGraphVoList(graphVoList);

		return apartmentDetailVo;
	}

	@Override
	public void removeByIdInfo(Long id) {
		// 查询当前被删除的公寓是否有房间 如果有房间提示不能删除
		Long roomCnt = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));
		if(roomCnt>0){
			// 有房间 不能删除
			// 抛出自定义异常 也就是抛出业务异常
			throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
		}
		// 删除公寓信息
		this.removeById(id);

		// 还要删除当前公寓关联表的信息【关系表】

		// 删除公寓配套关系表信息
		apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId, id));
		// 删除公寓标签关系表信息
		apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id));
		// 删除公寓杂费关系表信息
		apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId, id));
		// 删除公寓图片关系表信息
		graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId, id).eq(GraphInfo::getItemType, ItemType.APARTMENT));



	}


}






